<template>
  <div class="department-tree-container">
    <div class="tree-header">
      <h3 class="tree-title">部门架构</h3>
    </div>

    <div class="tree-content">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange" class="department-tabs">
        <el-tab-pane label="内部部门" name="internal">
          <el-tree
            ref="internalTreeRef"
            :data="internalTreeData"
            :props="treeProps"
            :default-expanded-keys="defaultExpandedKeys"
            :highlight-current="true"
            :expand-on-click-node="false"
            node-key="id"
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="tree-node">
                <span class="node-title">{{ data.title }}</span>
                <span v-if="data.user_count > 0" class="user-count">({{ data.user_count }})</span>
              </span>
            </template>
          </el-tree>
        </el-tab-pane>
        <el-tab-pane label="外联部门" name="external">
          <el-tree
            ref="externalTreeRef"
            :data="externalTreeData"
            :props="treeProps"
            :default-expanded-keys="defaultExpandedKeys"
            :highlight-current="true"
            :expand-on-click-node="false"
            node-key="id"
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="tree-node">
                <span class="node-title">{{ data.title }}</span>
                <span v-if="data.user_count > 0" class="user-count">({{ data.user_count }})</span>
              </span>
            </template>
          </el-tree>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import { useUserStore } from '@/store/user'

  interface DepartmentNode {
    id: number
    title: string
    parent_id: number
    children?: DepartmentNode[]
    user_count: number
    type?: number // 增加type字段，用于区分内部部门和外联部门
  }

  interface Props {
    selectedId?: number | null
  }

  interface Emits {
    (e: 'select-department', id: number | null): void
  }

  const props = withDefaults(defineProps<Props>(), {
    selectedId: null,
  })

  const emit = defineEmits<Emits>()
  const userStore = useUserStore()

  // 响应式数据
  const internalTreeRef = ref()
  const externalTreeRef = ref()
  const internalTreeData = ref<DepartmentNode[]>([]) // 内部部门数据
  const externalTreeData = ref<DepartmentNode[]>([]) // 外联部门数据
  const loading = ref(false)
  const defaultExpandedKeys = ref<number[]>([])
  const activeTab = ref('internal') // 默认选中内部部门标签页

  // 树配置
  const treeProps = {
    label: 'title',
    children: 'children',
    key: 'id',
  }

  // 加载部门树数据
  const loadDepartmentTree = async () => {
    loading.value = true
    try {
      const res: any = await userStore.getDepartmentListAction()
      if (res.code === 0) {
        // 转换部门数据为树节点格式
        const convertToTreeNodes = (departments: any[]): DepartmentNode[] => {
          return departments.map(dept => ({
            id: dept.id,
            title: dept.title,
            parent_id: dept.pid,
            type: dept.type || 1, // 如果没有type字段，默认为1（内部部门）
            children: dept.children ? convertToTreeNodes(dept.children) : [],
            user_count: 0, // 将在 loadUserCounts 中更新
          }))
        }

        const allTreeData = convertToTreeNodes(res.data || [])

        // 分离内部和外联部门数据
        filterDepartmentsByType(allTreeData)

        // 设置默认展开第一级
        if (activeTab.value === 'internal' && internalTreeData.value.length > 0) {
          defaultExpandedKeys.value = internalTreeData.value.map(item => item.id)
        } else if (activeTab.value === 'external' && externalTreeData.value.length > 0) {
          defaultExpandedKeys.value = externalTreeData.value.map(item => item.id)
        }

        // 加载用户统计
        await loadUserCounts()
      } else {
        ElMessage.error(res.msg || '加载部门数据失败')
      }
    } catch (error) {
      ElMessage.error('加载部门数据失败')
      console.error('加载部门数据失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 根据部门类型过滤数据
  const filterDepartmentsByType = (departments: DepartmentNode[]) => {
    const internal: DepartmentNode[] = []
    const external: DepartmentNode[] = []

    // 递归处理每个部门及其子部门
    const processNode = (node: DepartmentNode, parentType: number = 1): DepartmentNode => {
      // 如果节点没有type字段，使用父节点的type
      const nodeType = node.type || parentType

      // 创建新节点副本，避免引用问题
      const newNode: DepartmentNode = {
        ...node,
        type: nodeType,
        children: [],
      }

      // 如果有子节点，递归处理
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
          const processedChild = processNode(child, nodeType)
          if (processedChild) {
            newNode.children!.push(processedChild)
          }
        })
      }

      return newNode
    }

    // 处理所有根节点
    departments.forEach(dept => {
      const processedNode = processNode(dept)
      if (processedNode.type === 2) {
        external.push(processedNode)
      } else {
        internal.push(processedNode)
      }
    })

    internalTreeData.value = internal
    externalTreeData.value = external
  }

  // 加载用户数量统计
  const loadUserCounts = async () => {
    try {
      // 获取所有用户的部门统计
      const res = await userStore.getUserListAction({ page: 1, limit: 1000 })
      if (res.code === 0) {
        // 修复：从 res.data.list 中获取用户数组
        const users = res.data.list || []
        const deptCountMap = new Map<number, number>()

        // 统计每个部门的用户数
        users.forEach((user: any) => {
          if (user.did) {
            deptCountMap.set(user.did, (deptCountMap.get(user.did) || 0) + 1)
          }
        })

        // 更新树节点中的用户数量
        const updateCounts = (nodes: DepartmentNode[]) => {
          nodes.forEach(node => {
            node.user_count = deptCountMap.get(node.id) || 0
            if (node.children && node.children.length > 0) {
              updateCounts(node.children)
            }
          })
        }

        updateCounts(internalTreeData.value)
        updateCounts(externalTreeData.value)
      }
    } catch (error) {
      console.error('加载用户统计失败:', error)
      ElMessage.error('加载用户统计失败')
    }
  }

  // 处理节点点击
  const handleNodeClick = (data: DepartmentNode) => {
    const isAlreadySelected = props.selectedId === data.id

    if (isAlreadySelected) {
      // 如果点击已选中的节点，取消选择
      emit('select-department', null)
      setSelectedNode(null)
    } else {
      // 选择新部门
      emit('select-department', data.id)
    }
  }

  // 处理标签页切换
  const handleTabChange = (tabName: string) => {
    // 切换标签页时重置部门选中状态
    emit('select-department', null)
    setSelectedNode(null)

    // 设置展开节点
    if (tabName === 'internal' && internalTreeData.value.length > 0) {
      defaultExpandedKeys.value = internalTreeData.value.map(item => item.id)
    } else if (tabName === 'external' && externalTreeData.value.length > 0) {
      defaultExpandedKeys.value = externalTreeData.value.map(item => item.id)
    }
  }

  // 设置选中节点
  const setSelectedNode = (id: number | null) => {
    // 根据当前标签页选择对应的树组件
    if (activeTab.value === 'internal' && internalTreeRef.value) {
      internalTreeRef.value.setCurrentKey(id)
    } else if (activeTab.value === 'external' && externalTreeRef.value) {
      externalTreeRef.value.setCurrentKey(id)
    }
  }

  // 监听外部选中ID变化
  watch(
    () => props.selectedId,
    newId => {
      setSelectedNode(newId)
    }
  )

  // 暴露方法给父组件
  defineExpose({
    setSelectedNode,
  })

  onMounted(() => {
    loadDepartmentTree()
  })
</script>

<style scoped>
  .department-tree-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    padding: 16px;
    box-sizing: border-box;
  }

  .tree-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 8px 12px 8px;
    border-bottom: 1px solid #e4e7ed;
    margin-bottom: 12px;
  }

  .tree-title {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }

  .tree-node {
    display: flex;
    align-items: center;
    gap: 4px;
  }

  .user-count {
    color: #909399;
    font-size: 12px;
  }

  .tree-content {
    flex: 1;
    overflow: hidden;
    min-height: 0;
  }

  /* 标签页样式 */
  .department-tabs {
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  :deep(.el-tabs__content) {
    flex: 1;
    overflow: auto;
    padding: 8px 0;
  }

  :deep(.el-tabs__header) {
    margin-bottom: 12px;
  }

  :deep(.el-tabs__nav) {
    width: 100%;
  }

  :deep(.el-tabs__item) {
    flex: 1;
    text-align: center;
  }

  :deep(.el-tree) {
    background-color: transparent;
  }

  /* 优化滚动条样式 */
  :deep(.el-tree)::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  :deep(.el-tree)::-webkit-scrollbar-track {
    background: #f5f7fa;
    border-radius: 3px;
  }

  :deep(.el-tree)::-webkit-scrollbar-thumb {
    background: #c0c4cc;
    border-radius: 3px;
  }

  :deep(.el-tree)::-webkit-scrollbar-thumb:hover {
    background: #909399;
  }
</style>
